package com.ehouse;

import java.util.HashMap;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.Toast;

import com.ehouse.connection.ConnectionService;
import com.ehouse.connection.ConnectionService.IConnectionResponseListener;
import com.ehouse.database.IrrigationTable;
import com.ehouse.database.LightTable;
import com.ehouse.database.TemperatureTable;
import com.ehouse.database.WindowTable;
import com.ehouse.fragments.IrrigationsFragment;
import com.ehouse.fragments.LightsFragment;
import com.ehouse.fragments.TemperaturesFragment;
import com.ehouse.fragments.WindowsFragment;
import com.ehouse.models.Settings;
import com.ehouse.push.NotificationsService;
import com.google.android.gcm.GCMRegistrar;

public class MainActivity extends FragmentActivity 
	implements NotificationsService.NotificationListener{
	public static NotificationsService.NotificationListener notificationsListener;
	public static final String LOG_TAG = "MAIN_ACTIVITY";
	public static final boolean DEBUG = false;
	private boolean receivedRegId = false;
	private boolean connected = false;
	private TabHost tabHost;
	
	public MainActivity() {
		super();
		notificationsListener = this;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		registerForNotification();
		initializeInterface();
    }
    
    @Override
    public void onResume(){
    	super.onResume();
 
        Intent bindIntent = new Intent(this, ConnectionService.class);
        bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
        
        reloadFragments();
    }
    
    private void reloadFragments(){
    	MainActivity.this.runOnUiThread(new Runnable() {
    	       public void run() {
    	    	   FragmentManager fragmentManager = getSupportFragmentManager();
    	           TemperaturesFragment templistFragment = (TemperaturesFragment)fragmentManager.findFragmentById(R.id.temperatures_fragment);
    	           templistFragment.reload();
    	           LightsFragment lightslistFragment = (LightsFragment)fragmentManager.findFragmentById(R.id.lights_fragment);
    	           lightslistFragment.reload();
    	           IrrigationsFragment irrigationlistFragment = (IrrigationsFragment)fragmentManager.findFragmentById(R.id.irrigations_fragment);
    	           irrigationlistFragment.reload();
    	           WindowsFragment windowslistFragment = (WindowsFragment)fragmentManager.findFragmentById(R.id.windows_fragment);
    	           windowslistFragment.reload();
    	       }
    	     });
    	
    }
    
    private void loadDataFromServer(){
    	serviceRef.getLights(new IConnectionResponseListener() {
			
			public void responseReceived(Object data, boolean success) {
				if(success){
					reloadFragments();
					}
			}
		});
    	
    	serviceRef.getTemperature(new IConnectionResponseListener() {
			
			public void responseReceived(Object data, boolean success) {
				if(success){
					reloadFragments();
					}
			}
		});
    	
    	serviceRef.getIrrigation(new IConnectionResponseListener() {
			
			public void responseReceived(Object data, boolean success) {
				if(success){
					reloadFragments();
					}
			}
		});
    	
    	serviceRef.getWindows(new IConnectionResponseListener() {
			
			public void responseReceived(Object data, boolean success) {
				if(success){
					reloadFragments();
					}
			}
		});
    	
    	serviceRef.loadRules("Lights", new IConnectionResponseListener() {
			
			public void responseReceived(Object data, boolean success) {
				if(success){
				//	we got new schedules
					}
			}
		});
    	
		serviceRef.loadRules("Temperature", new IConnectionResponseListener() {
					
					public void responseReceived(Object data, boolean success) {
						if(success){
							//	we got new schedules
						}
						}
				});
		    	
		serviceRef.loadRules("Irrigation", new IConnectionResponseListener() {
			
			public void responseReceived(Object data, boolean success) {
				if(success){
						//	we got new schedules
					}
			}
		});

    }
    
    @Override
    public void onPause(){
    	super.onPause();
    	if(serviceRef != null){
    		serviceRef.closeConnection();
    		unbindService(mConnection);
    	}
    	serviceRef = null;
    	connected = false;
    }
    
    //Service connection
    public static ConnectionService serviceRef;
    
    
    private ServiceConnection mConnection = new ServiceConnection() {
     public void onServiceConnected(ComponentName className, 
                                    IBinder service) {
       // Called when the connection is made.
       serviceRef = ((ConnectionService.ConnectionBinder)service).getService();
       onBinding();
     }
     
     public void onServiceDisconnected(ComponentName className) {

       // Received when the service unexpectedly disconnects.
       serviceRef = null;
     }
    };
    
    
	public void onBinding() {
		final SharedPreferences sharedPrefs = PreferenceManager
				.getDefaultSharedPreferences(MainActivity.this);
		String ip = sharedPrefs.getString(Settings.IP, "");

		if (ip.length() > 0) {
			serviceRef.openConnection(ip, new IConnectionResponseListener() {

				public void responseReceived(Object data, boolean success) {
					if (success) {
						if (receivedRegId) {
							sendRegistrationId(sharedPrefs.getString(
									NotificationsService.REG_ID, ""));
						}
						connected = true;
						loadDataFromServer();
					} else {
						connected = false;
						MainActivity.this.runOnUiThread(new Runnable() {
						    public void run() {
						    	if(!DEBUG)
						    		startActivity(new Intent(MainActivity.this, PreferencesActivity.class));
								Toast.makeText(MainActivity.this,
								R.string.connection_error, Toast.LENGTH_LONG)
								.show();
						    }
						});

					}
				}
			});
		} else {
			startActivity(new Intent(MainActivity.this,
					PreferencesActivity.class));
		}
	}
	
	private void loadDummyData(){
		ContentResolver cr = getContentResolver();
    
		String[] lightItems = getResources().getStringArray(R.array.lightItems);
		HashMap<String, Boolean> map = new HashMap<String, Boolean>();
		for (String s : lightItems) {
			map.put(s, true);
		}
    LightTable.update(cr, map);
    
    int[]temperatureItems = getResources().getIntArray(R.array.temperatureItems);
    //String[]labelsSwitches = new String[]{getResources().getString(R.string.a_c), getResources().getString(R.string.heating)};
    HashMap<String, String> map2 = new HashMap<String, String>();
    map2.put("VALUE", Integer.toString(temperatureItems[0]));
    map2.put(getResources().getString(R.string.a_c), "true");
    map2.put(getResources().getString(R.string.heating), "true");
    TemperatureTable.update(cr, map2);
    
    int[]irrigationItems = getResources().getIntArray(R.array.irrigationItems);
    IrrigationTable.update(cr, irrigationItems);
    
    String[]windowItems = getResources().getStringArray(R.array.windowItems);
    map = new HashMap<String, Boolean>();
    for (String s : windowItems) {
    	map.put(s, true);
    }
    WindowTable.update(cr, map);		
    
	}

    
    public void initializeInterface()
    {
    	if(DEBUG)
    		loadDummyData();
    	
    	tabHost=(TabHost)findViewById(R.id.tabHost);
    	tabHost.setup();
    	tabHost.invalidate();

    	//Lights Tab
    	TabSpec lights=tabHost.newTabSpec("LightsTab");
    	lights.setIndicator(getResources().getString(R.string.lights_tab), getResources().getDrawable(R.drawable.ic_tab_lights));
    	lights.setContent(R.id.lights_fragment);
    	tabHost.addTab(lights);
  
    	//Temperatures tab
    	TabSpec spec2=tabHost.newTabSpec("TemperatureTab");
    	spec2.setIndicator(getResources().getString(R.string.temps_tab), getResources().getDrawable(R.drawable.ic_tab_temp));
    	spec2.setContent(R.id.temperatures_fragment);
    	tabHost.addTab(spec2);
    	
    	//Irrigation tab
    	TabSpec spec3=tabHost.newTabSpec("IrrigationsTab");
    	spec3.setIndicator(getResources().getString(R.string.irigs_tab), getResources().getDrawable(R.drawable.ic_tab_irri));
    	spec3.setContent(R.id.irrigations_fragment);
    	tabHost.addTab(spec3);
    	
    	//Windows tab
    	TabSpec spec4=tabHost.newTabSpec("WindowsTab");
    	spec4.setIndicator(getResources().getString(R.string.windows_tab), getResources().getDrawable(R.drawable.ic_tab_windows));
    	spec4.setContent(R.id.windows_fragment);
    	tabHost.addTab(spec4);
    	
    }
    
	public void registerForNotification() {
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);
		final String regId = GCMRegistrar.getRegistrationId(this);
		if (regId.equals("")) {
			GCMRegistrar.register(this, "477106032145");
		} else {
			Log.v(NotificationsService.LOG_ID, "Already registered");
			receivedRegistrationId(regId);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_refresh:
			if(connected)
				loadDataFromServer();
			return true;
		case R.id.menu_settings:
			startActivity(new Intent(this, PreferencesActivity.class));
			return true;
		case R.id.menu_schedule:
			startActivity(new Intent(this, ScheduleActivity.class));
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void receivedRegistrationId(String regId) {
		receivedRegId = true;
		if (serviceRef != null && connected)
			sendRegistrationId(regId);
	}

	public void sendRegistrationId(String regId) {
		serviceRef.sendRegId(regId, new IConnectionResponseListener() {

			public void responseReceived(Object data, boolean success) {
					//nothing
			}
		});
	}
	


}
